package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${out_put_path}")
    private String outPutPath;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        PageHelper.startPage(currentPage,pageSize);
        Page<Setmeal> page = setmealDao.queryByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.add(setmeal);
        this.setSetmealAndCheckGroup(setmeal,checkgroupIds);
        //将图片名称保存到Redis集合中
        String fileName = setmeal.getImg();
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,fileName);

        //当添加套餐后需要重新生成静态页面（套餐列表页面、套餐详情页面）
        //generateMobileStaticHtml();
    }

    //生成当前方法所需的静态页面
    public void generateMobileStaticHtml() {
        //在生成静态页面之前需要查询数据
        List<Setmeal> list = setmealDao.findAll();

        //生成套餐列表静态页面
        generateMobileSetmealListHtml(list);

        //生成套餐详情静态页面
        generateMobileSetmealDetailHtml(list);
    }

    public void generateMobileSetmealDetailHtml(List<Setmeal> list) {
        for (Setmeal setmeal : list) {
            Map map = new HashMap();
            map.put("setmeal",setmealDao.findById(setmeal.getId()));
            generateStaticHtml("mobile_setmeal_detail.ftl","setmeal_detail_" + setmeal.getId() + ".html",map);
        }
    }

    public void generateMobileSetmealListHtml(List<Setmeal> list) {
        Map map = new HashMap();
        map.put("setmealList",list);
        generateStaticHtml("mobile_setmeal.ftl","m_setmeal.html",map);
    }

    //通用的方法，用于生成静态页面
    public void generateStaticHtml(String templateName, String htmlPageName, Map map){
        //获得配置对象
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        Writer out = null;
        try{
            Template template = configuration.getTemplate(templateName);
            //构造输出流
            out = new FileWriter(new File(outPutPath + "/" + htmlPageName));
            //输出文件
            template.process(map,out);
            out.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    @Override
    public void setSetmealAndCheckGroup(Setmeal setmeal, Integer[] checkgroupIds) {
        Integer setmealId = setmeal.getId();
        for (Integer checkgroupId : checkgroupIds) {
            setmealDao.setSetmealAndCheckGroup(setmealId,checkgroupId);
        }
    }

    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    @Override
    public Setmeal findById(int id) {
        return setmealDao.findById(id);
    }

    @Override
    public void deleteById(int id) {
        long count = setmealDao.findCountBySetmealId(id);

        if(count > 0){
            new RuntimeException();
        }
        setmealDao.deleteById(id);
    }

    @Override
    public Setmeal findBySetmealId(int id) {
        return setmealDao.findBySetmealId(id);
    }

    @Override
    public List<Integer> findCheckGroupIdsBySetmealId(int id) {
        return setmealDao.findCheckGroupIdsBySetmealId(id);
    }

    @Override
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        //操作修改检查组，操作t_checkgroup表
        setmealDao.edit(setmeal);
        //清理当前检查组关联的检查项，操作中间关系表t_checkgroup_checkitem表
        setmealDao.deleteAssociation(setmeal.getId());
        //重新建立当前检查组和检查项的关联关系
        setSetmealAndCheckGroup(setmeal,checkgroupIds);
    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setmealDao.findSetmealCount();
    }

}
